#include "../../source/server.hpp"
#include <pthread.h>
#include <string>
#include <vector>


void OnMessage(const Connection::Ptr &conn, Buffer *buff)
{
    DBG_LOG("%s", buff->ReadPosition());
    buff->MoveReadOffset(buff->ReadAbleSize());
    std::string str = "message";
    conn->Send(str.c_str(), str.size());
}
void OnConnected(const Connection::Ptr &conn)
{
    DBG_LOG("new Connection : %p", conn.get());
}

uint64_t conn_id = 0;
EventLoop base_loop;
std::vector<LoopThread> threads(2);
int next_loop = 0;
LoopThreadPool *loop_pool;

//管理所有的连接
std::unordered_map<uint64_t, Connection::Ptr> _conns;
void ConnectionDestroy(const Connection::Ptr &conn)
{
    _conns.erase(conn->Id());
}
void NewConnection(int fd)
{
    // //fd = socketfd
    // int fd = lst_channel->Fd();
    // int newfd = accept(fd, NULL, NULL);
    // if(newfd < 0)
    //     return;

    conn_id++;
    Connection::Ptr conn(new Connection(loop_pool->NextLoop(), conn_id, fd));
    conn->SetMessageCallBack(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallBack(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established(); //就绪初始化
    _conns.insert({conn_id, conn});
    DBG_LOG("%p, is same thread with main thread", (void*)pthread_self());
}

int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    Acceptor accptor(&base_loop, 8080);
    accptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));
    accptor.Listen();
    base_loop.Start();
    return 0;
}